﻿using System.Windows;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using KinonekoSoftware.ArkSpark.Core;
using KinonekoSoftware.Foundation.UI.Controls.Selectors;

namespace KinonekoSoftware.ArkSpark.Controls
{
    public class DocumentEditor : ForestListBox
    {
        public static readonly StyledProperty<IResourceDictionary> EditingResourcesProperty;
        public static readonly StyledProperty<IArkSparkMQ>         MessageBusProperty;


        static DocumentEditor()
        {
            EditingResourcesProperty = AvaloniaProperty.Register<DocumentEditor, IResourceDictionary>(nameof(EditingResources));
            MessageBusProperty       = AvaloniaProperty.Register<DocumentEditor, IArkSparkMQ>(nameof(MessageBus));

            MessageBusProperty.Changed.Subscribe(x =>
            {
                var old = x.GetOldValue<IArkSparkMQ>();

                if (old is not null)
                {
                    //
                    // 清空引用
                    old.ForwardHandler = null;
                }
                
                OnMessageBusChanged(x.Sender as DocumentEditor, x.GetNewValue<IArkSparkMQ>());
            });
        }

        private static void OnMessageBusChanged(DocumentEditor editor, IArkSparkMQ bus)
        {
            if (editor is null || bus is null)
            {
                return;
            }

            //
            //
            bus.ForwardHandler = editor.OnEventHandler;
        }


        private void OnEventHandler(IArkSparkEvent @event)
        {
            if (@event is not NewSelectionEventArgs args)
            {
                return;
            }

            //
            //
            SelectedItem = args.EditingItem;
        }

        protected override TemplatedControl CreateContainerForItemOverride(object item, int index, object recycleKey)
        {
            return new DocumentEditorItem();
        }

        protected override bool NeedsContainerOverride(object item, int index, out object recycleKey)
        {
            return NeedsContainer<DocumentEditorItem>(item, out recycleKey);
        }
        
        public IResourceDictionary EditingResources
        {
            get
            {
                var val = GetValue(EditingResourcesProperty);

                if (val is null)
                {
                    val = new ResourceDictionary();
                    SetValue(EditingResourcesProperty, val);
                }

                return val;
            }
            set => SetValue(EditingResourcesProperty, value);
        }
        

        public IArkSparkMQ MessageBus
        {
            get => GetValue(MessageBusProperty);
            set => SetValue(MessageBusProperty, value);
        }
    }
}